from model.mail_model import Mail
from database_connection.index import Session
from utils.utils import add_model


session = Session()


def add_one_mail(mail_info):
    try:
        mail = add_model(mail_info, "mail")
        session.add(mail)
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
        # 将错误信息返回给前端
    else:
        session.commit()
        session.flush()
        session.refresh(mail)
        return {"msg": "success", "data": mail}


def find_one_mail(mail_query_criteria):
    try:
        data = session.query(Mail).filter_by(**mail_query_criteria).first()
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
        # 将错误信息返回给前端
    else:
        return {"msg": "success", "data": data}


def update_one_mail(mail_query_criteria, mail_update_criteria):
    try:
        session.query(Mail).filter_by(**mail_query_criteria).update(mail_update_criteria)
    except Exception as e:
        session.rollback()
        return {"msg": "error"}
        # 将错误信息返回给前端
    else:
        session.commit()
        data = session.query(Mail).filter_by(**mail_query_criteria).first()
        return {"msg": "success", "data": data}
